Binary Search Tree Iterator
Question
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
Analysis
- 利用栈保存根节点的所有直接左节点
- 判断是否存在next节点可以直接通过栈是否为空来判断
- next函数在pop当前节点后push该节点的所有直接左节点
Code
|
|
Binary Tree Zigzag Level Order Traversal
Question
Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7],
|
|
return its zigzag level order traversal as:
|
|
Analysis
- 利用linkedlist来保存每层的节点,偶数层的节点从前向后插入,奇数层节点每次插入在头节点处
- 利用两个变量parent,child来记录每层节点个数,从而确定从queue中poll的次数,parent保存当前层的节点个数,child保存下一层的节点个数
- 在一开始的时候判断root是否为空
Code
|
|